<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1" />
<meta name="generator" content="pdoc 0.9.1" />
<title>tronpytool.common.encoding API documentation</title>
<meta name="description" content="" />
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/sanitize.min.css" integrity="sha256-PK9q560IAAa6WVRRh76LtCaI8pjTJ2z11v0miyNNjrs=" crossorigin>
<link rel="preload stylesheet" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/11.0.1/typography.min.css" integrity="sha256-7l/o7C8jubJiy74VsKTidCy1yBkRtiUGbVkYBylBqUg=" crossorigin>
<link rel="stylesheet preload" as="style" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/styles/github.min.css" crossorigin>
<style>:root{--highlight-color:#fe9}.flex{display:flex !important}body{line-height:1.5em}#content{padding:20px}#sidebar{padding:30px;overflow:hidden}#sidebar > *:last-child{margin-bottom:2cm}.http-server-breadcrumbs{font-size:130%;margin:0 0 15px 0}#footer{font-size:.75em;padding:5px 30px;border-top:1px solid #ddd;text-align:right}#footer p{margin:0 0 0 1em;display:inline-block}#footer p:last-child{margin-right:30px}h1,h2,h3,h4,h5{font-weight:300}h1{font-size:2.5em;line-height:1.1em}h2{font-size:1.75em;margin:1em 0 .50em 0}h3{font-size:1.4em;margin:25px 0 10px 0}h4{margin:0;font-size:105%}h1:target,h2:target,h3:target,h4:target,h5:target,h6:target{background:var(--highlight-color);padding:.2em 0}a{color:#058;text-decoration:none;transition:color .3s ease-in-out}a:hover{color:#e82}.title code{font-weight:bold}h2[id^="header-"]{margin-top:2em}.ident{color:#900}pre code{background:#f8f8f8;font-size:.8em;line-height:1.4em}code{background:#f2f2f1;padding:1px 4px;overflow-wrap:break-word}h1 code{background:transparent}pre{background:#f8f8f8;border:0;border-top:1px solid #ccc;border-bottom:1px solid #ccc;margin:1em 0;padding:1ex}#http-server-module-list{display:flex;flex-flow:column}#http-server-module-list div{display:flex}#http-server-module-list dt{min-width:10%}#http-server-module-list p{margin-top:0}.toc ul,#index{list-style-type:none;margin:0;padding:0}#index code{background:transparent}#index h3{border-bottom:1px solid #ddd}#index ul{padding:0}#index h4{margin-top:.6em;font-weight:bold}@media (min-width:200ex){#index .two-column{column-count:2}}@media (min-width:300ex){#index .two-column{column-count:3}}dl{margin-bottom:2em}dl dl:last-child{margin-bottom:4em}dd{margin:0 0 1em 3em}#header-classes + dl > dd{margin-bottom:3em}dd dd{margin-left:2em}dd p{margin:10px 0}.name{background:#eee;font-weight:bold;font-size:.85em;padding:5px 10px;display:inline-block;min-width:40%}.name:hover{background:#e0e0e0}dt:target .name{background:var(--highlight-color)}.name > span:first-child{white-space:nowrap}.name.class > span:nth-child(2){margin-left:.4em}.inherited{color:#999;border-left:5px solid #eee;padding-left:1em}.inheritance em{font-style:normal;font-weight:bold}.desc h2{font-weight:400;font-size:1.25em}.desc h3{font-size:1em}.desc dt code{background:inherit}.source summary,.git-link-div{color:#666;text-align:right;font-weight:400;font-size:.8em;text-transform:uppercase}.source summary > *{white-space:nowrap;cursor:pointer}.git-link{color:inherit;margin-left:1em}.source pre{max-height:500px;overflow:auto;margin:0}.source pre code{font-size:12px;overflow:visible}.hlist{list-style:none}.hlist li{display:inline}.hlist li:after{content:',\2002'}.hlist li:last-child:after{content:none}.hlist .hlist{display:inline;padding-left:1em}img{max-width:100%}td{padding:0 .5em}.admonition{padding:.1em .5em;margin-bottom:1em}.admonition-title{font-weight:bold}.admonition.note,.admonition.info,.admonition.important{background:#aef}.admonition.todo,.admonition.versionadded,.admonition.tip,.admonition.hint{background:#dfd}.admonition.warning,.admonition.versionchanged,.admonition.deprecated{background:#fd4}.admonition.error,.admonition.danger,.admonition.caution{background:lightpink}</style>
<style media="screen and (min-width: 700px)">@media screen and (min-width:700px){#sidebar{width:30%;height:100vh;overflow:auto;position:sticky;top:0}#content{width:70%;max-width:100ch;padding:3em 4em;border-left:1px solid #ddd}pre code{font-size:1em}.item .name{font-size:1em}main{display:flex;flex-direction:row-reverse;justify-content:flex-end}.toc ul ul,#index ul{padding-left:1.5em}.toc > ul > li{margin-top:.5em}}</style>
<style media="print">@media print{#sidebar h1{page-break-before:always}.source{display:none}}@media print{*{background:transparent !important;color:#000 !important;box-shadow:none !important;text-shadow:none !important}a[href]:after{content:" (" attr(href) ")";font-size:90%}a[href][title]:after{content:none}abbr[title]:after{content:" (" attr(title) ")"}.ir a:after,a[href^="javascript:"]:after,a[href^="#"]:after{content:""}pre,blockquote{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}tr,img{page-break-inside:avoid}img{max-width:100% !important}@page{margin:0.5cm}p,h2,h3{orphans:3;widows:3}h1,h2,h3,h4,h5,h6{page-break-after:avoid}}</style>
<script defer src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/10.1.1/highlight.min.js" integrity="sha256-Uv3H6lx7dJmRfRvH8TH6kJD1TSK1aFcwgx+mdg3epi8=" crossorigin></script>
<script>window.addEventListener('DOMContentLoaded', () => hljs.initHighlighting())</script>
</head>
<body>
<main>
<article id="content">
<header>
<h1 class="title">Module <code>tronpytool.common.encoding</code></h1>
</header>
<section id="section-intro">
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">import json
import re
from typing import Union

from eth_account.datastructures import AttributeDict
from eth_utils import (
    hexstr_if_str,
    to_hex,
    big_endian_to_int,
    int_to_big_endian
)
from hexbytes import HexBytes
from trx_utils import (
    remove_0x_prefix,
    encode_hex,
    add_0x_prefix,
    decode_hex,
    is_boolean,
    is_integer,
    is_list_like,
    is_bytes
)

from tronpytool.common.abi import (
    size_of_type,
    sub_type_of_array_type,
    is_array_type,
    is_bool_type,
    is_uint_type,
    is_int_type,
    is_address_type,
    is_bytes_type,
    is_string_type
)
from tronpytool.common.toolz import (
    curry
)
from tronpytool.common.validation import assert_one_val
from tronpytool.common.validation import (
    validate_abi_type,
    validate_abi_value
)


def hex_encode_abi_type(abi_type, value, force_size=None):
    &#34;&#34;&#34;
    Encodes value into a hex string in format of abi_type
    &#34;&#34;&#34;
    validate_abi_type(abi_type)
    validate_abi_value(abi_type, value)

    data_size = force_size or size_of_type(abi_type)
    if is_array_type(abi_type):
        sub_type = sub_type_of_array_type(abi_type)
        return &#34;&#34;.join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value])
    elif is_bool_type(abi_type):
        return to_hex_with_size(value, data_size)
    elif is_uint_type(abi_type):
        return to_hex_with_size(value, data_size)
    elif is_int_type(abi_type):
        return to_hex_twos_compliment(value, data_size)
    elif is_address_type(abi_type):
        return pad_hex(value, data_size)
    elif is_bytes_type(abi_type):
        if is_bytes(value):
            return encode_hex(value)
        else:
            return value
    elif is_string_type(abi_type):
        return to_hex(text=value)
    else:
        raise ValueError(
            &#34;Unsupported ABI type: {0}&#34;.format(abi_type)
        )


def to_hex_twos_compliment(value, bit_size):
    &#34;&#34;&#34;
    Converts integer value to twos compliment hex representation with given bit_size
    &#34;&#34;&#34;
    if value &gt;= 0:
        return to_hex_with_size(value, bit_size)

    value = (1 &lt;&lt; bit_size) + value
    hex_value = hex(value)
    hex_value = hex_value.rstrip(&#34;L&#34;)
    return hex_value


def to_hex_with_size(value, bit_size):
    &#34;&#34;&#34;Converts a value to hex with given bit_size:&#34;&#34;&#34;
    return pad_hex(to_hex(value), bit_size)


def pad_hex(value, bit_size):
    &#34;&#34;&#34;Pads a hex string up to the given bit_size&#34;&#34;&#34;
    value = remove_0x_prefix(value)
    return add_0x_prefix(value.zfill(int(bit_size / 4)))


def trim_hex(hexstr):
    if hexstr.startswith(&#39;0x0&#39;):
        hexstr = re.sub(&#39;^0x0+&#39;, &#39;0x&#39;, hexstr)
        if hexstr == &#39;0x&#39;:
            hexstr = &#39;0x0&#39;
    return hexstr


def to_int(value=None, hexstr=None, text=None):
    &#34;&#34;&#34;Converts value to it&#39;s integer representation.

    Values are converted this way:

     * value:
       * bytes: big-endian integer
       * bool: True =&gt; 1, False =&gt; 0
     * hexstr: interpret hex as integer
     * text: interpret as string of digits, like &#39;12&#39; =&gt; 12
    &#34;&#34;&#34;
    assert_one_val(value, hexstr=hexstr, text=text)

    if hexstr is not None:
        return int(hexstr, 16)
    elif text is not None:
        return int(text)
    elif isinstance(value, bytes):
        return big_endian_to_int(value)
    elif isinstance(value, str):
        raise TypeError(&#34;Pass in strings with keyword hexstr or text&#34;)
    else:
        return int(value)


@curry
def text_if_str(to_type, text_or_primitive):
    &#34;&#34;&#34;Convert to a type, assuming that strings can be only unicode text (not a hexstr)&#34;&#34;&#34;
    if isinstance(text_or_primitive, str):
        (primitive, text) = (None, text_or_primitive)
    else:
        (primitive, text) = (text_or_primitive, None)
    return to_type(primitive, text=text)


def to_text(primitive=None, hexstr=None, text=None):
    assert_one_val(primitive, hexstr=hexstr, text=text)

    if hexstr is not None:
        return to_bytes(hexstr=hexstr).decode(&#39;utf-8&#39;)
    elif text is not None:
        return text
    elif isinstance(primitive, str):
        return to_text(hexstr=primitive)
    elif isinstance(primitive, bytes):
        return primitive.decode(&#39;utf-8&#39;)
    elif is_integer(primitive):
        byte_encoding = int_to_big_endian(primitive)
        return to_text(byte_encoding)
    raise TypeError(&#34;Expected an int, bytes or hexstr.&#34;)


def to_bytes(primitive=None, hexstr=None, text=None):
    assert_one_val(primitive, hexstr=hexstr, text=text)

    if is_boolean(primitive):
        return b&#39;\x01&#39; if primitive else b&#39;\x00&#39;
    elif isinstance(primitive, bytes):
        return primitive
    elif is_integer(primitive):
        return to_bytes(hexstr=to_hex(primitive))
    elif hexstr is not None:
        if len(hexstr) % 2:
            hexstr = &#39;0x0&#39; + remove_0x_prefix(hexstr)
        return decode_hex(hexstr)
    elif text is not None:
        return text.encode(&#39;utf-8&#39;)
    raise TypeError(&#34;expected an int in first arg, or keyword of hexstr or text&#34;)


def to_4byte_hex(hex_or_str_or_bytes: Union[int, str, bytes]) -&gt; str:
    size_of_4bytes = 4 * 8
    byte_str = hexstr_if_str(to_bytes, hex_or_str_or_bytes)
    if len(byte_str) &gt; 4:
        raise ValueError(
            &#39;expected value of size 4 bytes. Got: %d bytes&#39; % len(byte_str)
        )
    hex_str = encode_hex(byte_str)
    return pad_hex(hex_str, size_of_4bytes)


class FriendlyJsonSerialize:
    &#34;&#34;&#34;
    Friendly JSON serializer &amp; deserializer
    When encoding or decoding fails, this class collects
    information on which fields failed, to show more
    helpful information in the raised error messages.
    &#34;&#34;&#34;

    def _json_mapping_errors(self, mapping):
        for key, val in mapping.items():
            try:
                self._friendly_json_encode(val)
            except TypeError as exc:
                yield &#34;%r: because (%s)&#34; % (key, exc)

    def _json_list_errors(self, iterable):
        for index, element in enumerate(iterable):
            try:
                self._friendly_json_encode(element)
            except TypeError as exc:
                yield &#34;%d: because (%s)&#34; % (index, exc)

    def _friendly_json_encode(self, obj, cls=None):
        try:
            encoded = json.dumps(obj, cls=cls)
            return encoded
        except TypeError as full_exception:
            if hasattr(obj, &#39;items&#39;):
                item_errors = &#39;; &#39;.join(self._json_mapping_errors(obj))
                raise TypeError(&#34;dict had unencodable value at keys: {{{}}}&#34;.format(item_errors))
            elif is_list_like(obj):
                element_errors = &#39;; &#39;.join(self._json_list_errors(obj))
                raise TypeError(&#34;list had unencodable value at index: [{}]&#34;.format(element_errors))
            else:
                raise full_exception

    @staticmethod
    def json_decode(json_str):
        try:
            decoded = json.loads(json_str)
            return decoded
        except json.decoder.JSONDecodeError as exc:
            err_msg = &#39;Could not decode {} because of {}.&#39;.format(repr(json_str), exc)
            # Calling code may rely on catching JSONDecodeError to recognize bad json
            # so we have to re-raise the same type.
            raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos)

    def json_encode(self, obj, cls=None):
        try:
            return self._friendly_json_encode(obj, cls=cls)
        except TypeError as exc:
            raise TypeError(&#34;Could not encode to JSON: {}&#34;.format(exc))


class TronJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, AttributeDict):
            return {k: v for k, v in obj.items()}
        if isinstance(obj, HexBytes):
            return obj.hex()
        return json.JSONEncoder.default(self, obj)


def to_json(obj: object) -&gt; object:
    &#34;&#34;&#34;Convert a complex object (like a transaction object) to a JSON string&#34;&#34;&#34;
    return FriendlyJsonSerialize().json_encode(obj, cls=TronJsonEncoder)</code></pre>
</details>
</section>
<section>
</section>
<section>
</section>
<section>
<h2 class="section-title" id="header-functions">Functions</h2>
<dl>
<dt id="tronpytool.common.encoding.hex_encode_abi_type"><code class="name flex">
<span>def <span class="ident">hex_encode_abi_type</span></span>(<span>abi_type, value, force_size=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Encodes value into a hex string in format of abi_type</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def hex_encode_abi_type(abi_type, value, force_size=None):
    &#34;&#34;&#34;
    Encodes value into a hex string in format of abi_type
    &#34;&#34;&#34;
    validate_abi_type(abi_type)
    validate_abi_value(abi_type, value)

    data_size = force_size or size_of_type(abi_type)
    if is_array_type(abi_type):
        sub_type = sub_type_of_array_type(abi_type)
        return &#34;&#34;.join([remove_0x_prefix(hex_encode_abi_type(sub_type, v, 256)) for v in value])
    elif is_bool_type(abi_type):
        return to_hex_with_size(value, data_size)
    elif is_uint_type(abi_type):
        return to_hex_with_size(value, data_size)
    elif is_int_type(abi_type):
        return to_hex_twos_compliment(value, data_size)
    elif is_address_type(abi_type):
        return pad_hex(value, data_size)
    elif is_bytes_type(abi_type):
        if is_bytes(value):
            return encode_hex(value)
        else:
            return value
    elif is_string_type(abi_type):
        return to_hex(text=value)
    else:
        raise ValueError(
            &#34;Unsupported ABI type: {0}&#34;.format(abi_type)
        )</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.pad_hex"><code class="name flex">
<span>def <span class="ident">pad_hex</span></span>(<span>value, bit_size)</span>
</code></dt>
<dd>
<div class="desc"><p>Pads a hex string up to the given bit_size</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def pad_hex(value, bit_size):
    &#34;&#34;&#34;Pads a hex string up to the given bit_size&#34;&#34;&#34;
    value = remove_0x_prefix(value)
    return add_0x_prefix(value.zfill(int(bit_size / 4)))</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.text_if_str"><code class="name flex">
<span>def <span class="ident">text_if_str</span></span>(<span>to_type='__no__default__', text_or_primitive='__no__default__')</span>
</code></dt>
<dd>
<div class="desc"><p>Convert to a type, assuming that strings can be only unicode text (not a hexstr)</p></div>
</dd>
<dt id="tronpytool.common.encoding.to_4byte_hex"><code class="name flex">
<span>def <span class="ident">to_4byte_hex</span></span>(<span>hex_or_str_or_bytes: Union[int, str, bytes]) ‑> str</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_4byte_hex(hex_or_str_or_bytes: Union[int, str, bytes]) -&gt; str:
    size_of_4bytes = 4 * 8
    byte_str = hexstr_if_str(to_bytes, hex_or_str_or_bytes)
    if len(byte_str) &gt; 4:
        raise ValueError(
            &#39;expected value of size 4 bytes. Got: %d bytes&#39; % len(byte_str)
        )
    hex_str = encode_hex(byte_str)
    return pad_hex(hex_str, size_of_4bytes)</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.to_bytes"><code class="name flex">
<span>def <span class="ident">to_bytes</span></span>(<span>primitive=None, hexstr=None, text=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_bytes(primitive=None, hexstr=None, text=None):
    assert_one_val(primitive, hexstr=hexstr, text=text)

    if is_boolean(primitive):
        return b&#39;\x01&#39; if primitive else b&#39;\x00&#39;
    elif isinstance(primitive, bytes):
        return primitive
    elif is_integer(primitive):
        return to_bytes(hexstr=to_hex(primitive))
    elif hexstr is not None:
        if len(hexstr) % 2:
            hexstr = &#39;0x0&#39; + remove_0x_prefix(hexstr)
        return decode_hex(hexstr)
    elif text is not None:
        return text.encode(&#39;utf-8&#39;)
    raise TypeError(&#34;expected an int in first arg, or keyword of hexstr or text&#34;)</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.to_hex_twos_compliment"><code class="name flex">
<span>def <span class="ident">to_hex_twos_compliment</span></span>(<span>value, bit_size)</span>
</code></dt>
<dd>
<div class="desc"><p>Converts integer value to twos compliment hex representation with given bit_size</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_hex_twos_compliment(value, bit_size):
    &#34;&#34;&#34;
    Converts integer value to twos compliment hex representation with given bit_size
    &#34;&#34;&#34;
    if value &gt;= 0:
        return to_hex_with_size(value, bit_size)

    value = (1 &lt;&lt; bit_size) + value
    hex_value = hex(value)
    hex_value = hex_value.rstrip(&#34;L&#34;)
    return hex_value</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.to_hex_with_size"><code class="name flex">
<span>def <span class="ident">to_hex_with_size</span></span>(<span>value, bit_size)</span>
</code></dt>
<dd>
<div class="desc"><p>Converts a value to hex with given bit_size:</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_hex_with_size(value, bit_size):
    &#34;&#34;&#34;Converts a value to hex with given bit_size:&#34;&#34;&#34;
    return pad_hex(to_hex(value), bit_size)</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.to_int"><code class="name flex">
<span>def <span class="ident">to_int</span></span>(<span>value=None, hexstr=None, text=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Converts value to it's integer representation.</p>
<p>Values are converted this way:</p>
<ul>
<li>value:</li>
<li>bytes: big-endian integer</li>
<li>bool: True =&gt; 1, False =&gt; 0</li>
<li>hexstr: interpret hex as integer</li>
<li>text: interpret as string of digits, like '12' =&gt; 12</li>
</ul></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_int(value=None, hexstr=None, text=None):
    &#34;&#34;&#34;Converts value to it&#39;s integer representation.

    Values are converted this way:

     * value:
       * bytes: big-endian integer
       * bool: True =&gt; 1, False =&gt; 0
     * hexstr: interpret hex as integer
     * text: interpret as string of digits, like &#39;12&#39; =&gt; 12
    &#34;&#34;&#34;
    assert_one_val(value, hexstr=hexstr, text=text)

    if hexstr is not None:
        return int(hexstr, 16)
    elif text is not None:
        return int(text)
    elif isinstance(value, bytes):
        return big_endian_to_int(value)
    elif isinstance(value, str):
        raise TypeError(&#34;Pass in strings with keyword hexstr or text&#34;)
    else:
        return int(value)</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.to_json"><code class="name flex">
<span>def <span class="ident">to_json</span></span>(<span>obj: object) ‑> object</span>
</code></dt>
<dd>
<div class="desc"><p>Convert a complex object (like a transaction object) to a JSON string</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_json(obj: object) -&gt; object:
    &#34;&#34;&#34;Convert a complex object (like a transaction object) to a JSON string&#34;&#34;&#34;
    return FriendlyJsonSerialize().json_encode(obj, cls=TronJsonEncoder)</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.to_text"><code class="name flex">
<span>def <span class="ident">to_text</span></span>(<span>primitive=None, hexstr=None, text=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def to_text(primitive=None, hexstr=None, text=None):
    assert_one_val(primitive, hexstr=hexstr, text=text)

    if hexstr is not None:
        return to_bytes(hexstr=hexstr).decode(&#39;utf-8&#39;)
    elif text is not None:
        return text
    elif isinstance(primitive, str):
        return to_text(hexstr=primitive)
    elif isinstance(primitive, bytes):
        return primitive.decode(&#39;utf-8&#39;)
    elif is_integer(primitive):
        byte_encoding = int_to_big_endian(primitive)
        return to_text(byte_encoding)
    raise TypeError(&#34;Expected an int, bytes or hexstr.&#34;)</code></pre>
</details>
</dd>
<dt id="tronpytool.common.encoding.trim_hex"><code class="name flex">
<span>def <span class="ident">trim_hex</span></span>(<span>hexstr)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def trim_hex(hexstr):
    if hexstr.startswith(&#39;0x0&#39;):
        hexstr = re.sub(&#39;^0x0+&#39;, &#39;0x&#39;, hexstr)
        if hexstr == &#39;0x&#39;:
            hexstr = &#39;0x0&#39;
    return hexstr</code></pre>
</details>
</dd>
</dl>
</section>
<section>
<h2 class="section-title" id="header-classes">Classes</h2>
<dl>
<dt id="tronpytool.common.encoding.FriendlyJsonSerialize"><code class="flex name class">
<span>class <span class="ident">FriendlyJsonSerialize</span></span>
</code></dt>
<dd>
<div class="desc"><p>Friendly JSON serializer &amp; deserializer
When encoding or decoding fails, this class collects
information on which fields failed, to show more
helpful information in the raised error messages.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class FriendlyJsonSerialize:
    &#34;&#34;&#34;
    Friendly JSON serializer &amp; deserializer
    When encoding or decoding fails, this class collects
    information on which fields failed, to show more
    helpful information in the raised error messages.
    &#34;&#34;&#34;

    def _json_mapping_errors(self, mapping):
        for key, val in mapping.items():
            try:
                self._friendly_json_encode(val)
            except TypeError as exc:
                yield &#34;%r: because (%s)&#34; % (key, exc)

    def _json_list_errors(self, iterable):
        for index, element in enumerate(iterable):
            try:
                self._friendly_json_encode(element)
            except TypeError as exc:
                yield &#34;%d: because (%s)&#34; % (index, exc)

    def _friendly_json_encode(self, obj, cls=None):
        try:
            encoded = json.dumps(obj, cls=cls)
            return encoded
        except TypeError as full_exception:
            if hasattr(obj, &#39;items&#39;):
                item_errors = &#39;; &#39;.join(self._json_mapping_errors(obj))
                raise TypeError(&#34;dict had unencodable value at keys: {{{}}}&#34;.format(item_errors))
            elif is_list_like(obj):
                element_errors = &#39;; &#39;.join(self._json_list_errors(obj))
                raise TypeError(&#34;list had unencodable value at index: [{}]&#34;.format(element_errors))
            else:
                raise full_exception

    @staticmethod
    def json_decode(json_str):
        try:
            decoded = json.loads(json_str)
            return decoded
        except json.decoder.JSONDecodeError as exc:
            err_msg = &#39;Could not decode {} because of {}.&#39;.format(repr(json_str), exc)
            # Calling code may rely on catching JSONDecodeError to recognize bad json
            # so we have to re-raise the same type.
            raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos)

    def json_encode(self, obj, cls=None):
        try:
            return self._friendly_json_encode(obj, cls=cls)
        except TypeError as exc:
            raise TypeError(&#34;Could not encode to JSON: {}&#34;.format(exc))</code></pre>
</details>
<h3>Static methods</h3>
<dl>
<dt id="tronpytool.common.encoding.FriendlyJsonSerialize.json_decode"><code class="name flex">
<span>def <span class="ident">json_decode</span></span>(<span>json_str)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">@staticmethod
def json_decode(json_str):
    try:
        decoded = json.loads(json_str)
        return decoded
    except json.decoder.JSONDecodeError as exc:
        err_msg = &#39;Could not decode {} because of {}.&#39;.format(repr(json_str), exc)
        # Calling code may rely on catching JSONDecodeError to recognize bad json
        # so we have to re-raise the same type.
        raise json.decoder.JSONDecodeError(err_msg, exc.doc, exc.pos)</code></pre>
</details>
</dd>
</dl>
<h3>Methods</h3>
<dl>
<dt id="tronpytool.common.encoding.FriendlyJsonSerialize.json_encode"><code class="name flex">
<span>def <span class="ident">json_encode</span></span>(<span>self, obj, cls=None)</span>
</code></dt>
<dd>
<div class="desc"></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def json_encode(self, obj, cls=None):
    try:
        return self._friendly_json_encode(obj, cls=cls)
    except TypeError as exc:
        raise TypeError(&#34;Could not encode to JSON: {}&#34;.format(exc))</code></pre>
</details>
</dd>
</dl>
</dd>
<dt id="tronpytool.common.encoding.TronJsonEncoder"><code class="flex name class">
<span>class <span class="ident">TronJsonEncoder</span></span>
<span>(</span><span>*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)</span>
</code></dt>
<dd>
<div class="desc"><p>Extensible JSON <a href="http://json.org">http://json.org</a> encoder for Python data structures.</p>
<p>Supports the following objects and types by default:</p>
<p>+-------------------+---------------+
| Python
| JSON
|
+===================+===============+
| dict
| object
|
+-------------------+---------------+
| list, tuple
| array
|
+-------------------+---------------+
| str
| string
|
+-------------------+---------------+
| int, float
| number
|
+-------------------+---------------+
| True
| true
|
+-------------------+---------------+
| False
| false
|
+-------------------+---------------+
| None
| null
|
+-------------------+---------------+</p>
<p>To extend this to recognize other objects, subclass and implement a
<code>.default()</code> method with another method that returns a serializable
object for <code>o</code> if possible, otherwise it should call the superclass
implementation (to raise <code>TypeError</code>).</p>
<p>Constructor for JSONEncoder, with sensible defaults.</p>
<p>If skipkeys is false, then it is a TypeError to attempt
encoding of keys that are not str, int, float or None.
If
skipkeys is True, such items are simply skipped.</p>
<p>If ensure_ascii is true, the output is guaranteed to be str
objects with all incoming non-ASCII characters escaped.
If
ensure_ascii is false, the output can contain non-ASCII characters.</p>
<p>If check_circular is true, then lists, dicts, and custom encoded
objects will be checked for circular references during encoding to
prevent an infinite recursion (which would cause an OverflowError).
Otherwise, no such check takes place.</p>
<p>If allow_nan is true, then NaN, Infinity, and -Infinity will be
encoded as such.
This behavior is not JSON specification compliant,
but is consistent with most JavaScript based encoders and decoders.
Otherwise, it will be a ValueError to encode such floats.</p>
<p>If sort_keys is true, then the output of dictionaries will be
sorted by key; this is useful for regression tests to ensure
that JSON serializations can be compared on a day-to-day basis.</p>
<p>If indent is a non-negative integer, then JSON array
elements and object members will be pretty-printed with that
indent level.
An indent level of 0 will only insert newlines.
None is the most compact representation.</p>
<p>If specified, separators should be an (item_separator, key_separator)
tuple.
The default is (', ', ': ') if <em>indent</em> is <code>None</code> and
(',', ': ') otherwise.
To get the most compact JSON representation,
you should specify (',', ':') to eliminate whitespace.</p>
<p>If specified, default is a function that gets called for objects
that can't otherwise be serialized.
It should return a JSON encodable
version of the object or raise a <code>TypeError</code>.</p></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">class TronJsonEncoder(json.JSONEncoder):
    def default(self, obj):
        if isinstance(obj, AttributeDict):
            return {k: v for k, v in obj.items()}
        if isinstance(obj, HexBytes):
            return obj.hex()
        return json.JSONEncoder.default(self, obj)</code></pre>
</details>
<h3>Ancestors</h3>
<ul class="hlist">
<li>json.encoder.JSONEncoder</li>
</ul>
<h3>Methods</h3>
<dl>
<dt id="tronpytool.common.encoding.TronJsonEncoder.default"><code class="name flex">
<span>def <span class="ident">default</span></span>(<span>self, obj)</span>
</code></dt>
<dd>
<div class="desc"><p>Implement this method in a subclass such that it returns
a serializable object for <code>o</code>, or calls the base implementation
(to raise a <code>TypeError</code>).</p>
<p>For example, to support arbitrary iterators, you could
implement default like this::</p>
<pre><code>def default(self, o):
    try:
        iterable = iter(o)
    except TypeError:
        pass
    else:
        return list(iterable)
    # Let the base class default method raise the TypeError
    return JSONEncoder.default(self, o)
</code></pre></div>
<details class="source">
<summary>
<span>Expand source code</span>
</summary>
<pre><code class="python">def default(self, obj):
    if isinstance(obj, AttributeDict):
        return {k: v for k, v in obj.items()}
    if isinstance(obj, HexBytes):
        return obj.hex()
    return json.JSONEncoder.default(self, obj)</code></pre>
</details>
</dd>
</dl>
</dd>
</dl>
</section>
</article>
<nav id="sidebar">
<h1>Index</h1>
<div class="toc">
<ul></ul>
</div>
<ul id="index">
<li><h3>Super-module</h3>
<ul>
<li><code><a title="tronpytool.common" href="index.html">tronpytool.common</a></code></li>
</ul>
</li>
<li><h3><a href="#header-functions">Functions</a></h3>
<ul class="">
<li><code><a title="tronpytool.common.encoding.hex_encode_abi_type" href="#tronpytool.common.encoding.hex_encode_abi_type">hex_encode_abi_type</a></code></li>
<li><code><a title="tronpytool.common.encoding.pad_hex" href="#tronpytool.common.encoding.pad_hex">pad_hex</a></code></li>
<li><code><a title="tronpytool.common.encoding.text_if_str" href="#tronpytool.common.encoding.text_if_str">text_if_str</a></code></li>
<li><code><a title="tronpytool.common.encoding.to_4byte_hex" href="#tronpytool.common.encoding.to_4byte_hex">to_4byte_hex</a></code></li>
<li><code><a title="tronpytool.common.encoding.to_bytes" href="#tronpytool.common.encoding.to_bytes">to_bytes</a></code></li>
<li><code><a title="tronpytool.common.encoding.to_hex_twos_compliment" href="#tronpytool.common.encoding.to_hex_twos_compliment">to_hex_twos_compliment</a></code></li>
<li><code><a title="tronpytool.common.encoding.to_hex_with_size" href="#tronpytool.common.encoding.to_hex_with_size">to_hex_with_size</a></code></li>
<li><code><a title="tronpytool.common.encoding.to_int" href="#tronpytool.common.encoding.to_int">to_int</a></code></li>
<li><code><a title="tronpytool.common.encoding.to_json" href="#tronpytool.common.encoding.to_json">to_json</a></code></li>
<li><code><a title="tronpytool.common.encoding.to_text" href="#tronpytool.common.encoding.to_text">to_text</a></code></li>
<li><code><a title="tronpytool.common.encoding.trim_hex" href="#tronpytool.common.encoding.trim_hex">trim_hex</a></code></li>
</ul>
</li>
<li><h3><a href="#header-classes">Classes</a></h3>
<ul>
<li>
<h4><code><a title="tronpytool.common.encoding.FriendlyJsonSerialize" href="#tronpytool.common.encoding.FriendlyJsonSerialize">FriendlyJsonSerialize</a></code></h4>
<ul class="">
<li><code><a title="tronpytool.common.encoding.FriendlyJsonSerialize.json_decode" href="#tronpytool.common.encoding.FriendlyJsonSerialize.json_decode">json_decode</a></code></li>
<li><code><a title="tronpytool.common.encoding.FriendlyJsonSerialize.json_encode" href="#tronpytool.common.encoding.FriendlyJsonSerialize.json_encode">json_encode</a></code></li>
</ul>
</li>
<li>
<h4><code><a title="tronpytool.common.encoding.TronJsonEncoder" href="#tronpytool.common.encoding.TronJsonEncoder">TronJsonEncoder</a></code></h4>
<ul class="">
<li><code><a title="tronpytool.common.encoding.TronJsonEncoder.default" href="#tronpytool.common.encoding.TronJsonEncoder.default">default</a></code></li>
</ul>
</li>
</ul>
</li>
</ul>
</nav>
</main>
<footer id="footer">
<p>Generated by <a href="https://pdoc3.github.io/pdoc"><cite>pdoc</cite> 0.9.1</a>.</p>
</footer>
</body>
</html>